//
//  WalletViewController.m
//  dhfsAPP
//
//  Created by Devil on 2017/7/31.
//  Copyright © 2017年 Devil. All rights reserved.
//

//沙盒测试环境验证
#define SANDBOX @"https://sandbox.itunes.apple.com/verifyReceipt"
//正式环境验证
#define AppStore @"https://buy.itunes.apple.com/verifyReceipt"

#import "WalletViewController.h"
#import "fsapp-Swift.h"
#import <sqlite3.h>

static sqlite3 *db;

@interface WalletViewController (){
    NSString *insertNum;
}

@property(nonatomic,copy)NSString *productID;

@end

@implementation WalletViewController

#pragma mark - 懒加载
-(WalletView *)walletView{
    if (!_walletView) {
        _walletView = [[WalletView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        
        _walletView.walletViewDelegate = self;
    }
    
    return _walletView;
}

#pragma mark - 系统自动调用函数
- (void)viewDidLoad {
    [super viewDidLoad];
        self.navigationController.navigationBarHidden = YES;
    // Do any additional setup after loading the view.
    
    [self getPayHistory];
    [self getMoneyNum];
    [self.view addSubview:self.walletView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
#pragma mark WalletViewDelegate实现
-(void)backVC{
    [self dismissViewControllerAnimated:true completion:nil];
    [self.navigationController popViewControllerAnimated:true];

}

-(void)clickWalletViewBtn:(UIButton *)btn{
    
    if (btn.tag == WalletViewButtonTypeRecharge)
    {
        [self.walletView showRecharView:NO];
    }
    else if (btn.tag == WalletViewButtonTypeShut)
    {
        [self.walletView showRecharView:YES];
    }
    else if (btn.tag == WalletViewButtonTypeCurrent)
    {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        
        NSLog(@"%@",self.walletView.payMoney.text);
        int money = [[self.walletView.payMoney.text substringFromIndex:1]intValue];
        
        switch (money) {
            case 6:
                _productID = @"com.heiyou.dahan1";
                break;
                
            case 12:
                _productID = @"com.heiyou.dahan2";
                break;
            
            case 18:
                _productID = @"com.heiyou.dahan3";
                break;
            
            case 25:
                _productID = @"com.heiyou.dahan4";
                break;
            
            case 50:
                _productID = @"com.heiyou.dahan5";
                break;
                
            case 98:
                _productID = @"com.heiyou.dahan6";
                break;
                
            default:
                break;
        }
        
        if ([SKPaymentQueue canMakePayments])
        {
            [self requestProductData:_productID];
        }
        else
        {
            NSLog(@"不允许程序内付费");
        }
    }
    else if (btn.tag == WalletViewButtonTypeFind)
    {
        [self openDataBase];
        [self createTable];
        NSMutableArray *array = [[NSMutableArray alloc] init];
        array = [self search];
        [self closeDataBase];
        
        if (array.count == 0)
        {
            [SVProgressHUD setErrorImage:[UIImage imageNamed:@""]];
            [SVProgressHUD showErrorWithStatus:@"没有要找回的汉点"];
        }
        else
        {
            [self find:array];
        }
    }
    
}

-(void)chooseMoney:(UIButton *)btn{
    self.walletView.lastBtn.selected = NO;
    
    self.walletView.lastBtn.backgroundColor = [UIColor whiteColor];
    
    btn.selected = YES;
    
    btn.backgroundColor = RGB(0, 105, 193);
    
    self.walletView.lastBtn = btn;
    
    [self.walletView changePayMoney:btn.tag - 1000];
}

#pragma mark - 内购
//苹果服务器请求商品
-(void)requestProductData:(NSString *)type{
    NSLog(@"请求对应的产品信息");
    
    [SVProgressHUD showWithStatus:@"获取相应内购产品中"];
    
    NSArray *product = [[NSArray alloc] initWithObjects:type, nil];
    
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    
    request.delegate = self;
    
    [request start];
}

-(void)verifyPurchaseWithPaymentTransaction{
    //从沙河凭证中获取交易凭证并且拼接成实体数据
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];
    
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    //创建请求道苹果官方进行购买验证
    NSURL *url = [NSURL URLWithString:AppStore];
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody = bodyData;
    requestM.HTTPMethod = @"POST";
    
    //创建连接并发送同步请求
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
    {
        if (error)
        {
            NSLog(@"验证购买过程中发生错误，错误信息：%@",error);
            return ;
        }
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        if ([dic[@"status"] integerValue] == 0)
        {
            NSLog(@"购买成功");
            
            NSDictionary *dicReceipt = dic[@"receipt"];
            NSDictionary *dicInApp = [dicReceipt[@"in_app"] firstObject];
            
            //读取产品标识
            NSString *productIndentifier = dicInApp[@"product_id"];
            
            NSLog(@"%@",productIndentifier);
            //记录购买记录
            
            [self savePurchaseHistory:productIndentifier];
        }
        else
        {
            NSLog(@"购买失败，未通过验证");
        }
    }];
    
    [dataTask resume];
}

#pragma mark - SKPaymentTransactionObserver协议实现
//监听购买结果
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *tran in transactions)
    {
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
            {
                NSLog(@"交易成功");
                
                //发送到苹果服务器验证
                [self verifyPurchaseWithPaymentTransaction];
             
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
            break;
               
            case SKPaymentTransactionStatePurchasing:
            {
                NSLog(@"商品添加进列表");
             //   [[SKPaymentQueue defaultQueue] finishTransaction:tran];

            }
            break;
                
            case SKPaymentTransactionStateFailed:
            {
                NSLog(@"交易失败");
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                [SVProgressHUD showErrorWithStatus:@"购买失败"];
            }
                break;
            default:
                break;
        }
    }
}

-(void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}


#pragma mark - SKProductsRequestDelegate协议实现
//收到产品返回信息
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSLog(@"收到产品反馈消息");
    NSArray *product = response.products;
    if ([product count] == 0)
    {
        [SVProgressHUD dismiss];
        
        NSLog(@"没有商品");
        return;
    }
    
    NSLog(@"productID:%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量：%lu",[product count]);
    
    SKProduct *p = nil;
    
    for (SKProduct *pro in product)
    {
        NSLog(@"%@",[pro description]);
        NSLog(@"%@",[pro localizedTitle]);
        NSLog(@"%@",[pro localizedDescription]);
        NSLog(@"%@",[pro price]);
        NSLog(@"%@",[pro productIdentifier]);
        
        if ([pro.productIdentifier isEqualToString:_productID])
        {
            p = pro;
        }
    }
    
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    
    NSLog(@"发送购买请求");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
//请求失败
-(void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [SVProgressHUD showErrorWithStatus:@"支付失败"];
    NSLog(@"错误：%@",error);
}

-(void)requestDidFinish:(SKRequest *)request{
    [SVProgressHUD dismiss];
    NSLog(@"反馈信息结束");
}

#pragma mark - 获取服务器数据
-(void)savePurchaseHistory:(NSString *)productID{
    int num = 0;
    NSString *str = [NSString stringWithFormat:@"%@",productID];
    if ([productID isEqualToString:@"com.heiyou.dahan1"])
    {
        num = 6;
    }
    else if ([productID isEqualToString:@"com.heiyou.dahan2"])
    {
        num = 12;
    }
    else if ([productID isEqualToString:@"com.heiyou.dahan3"])
    {
        num = 18;
    }
    else if ([productID isEqualToString:@"com.heiyou.dahan4"])
    {
        num = 25;
    }
    else if ([productID isEqualToString:@"com.heiyou.dahan5"])
    {
        num = 50;
    }
    else if ([productID isEqualToString:@"com.heiyou.dahan6"])
    {
        num = 98;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    insertNum = [NSString stringWithFormat:@"%d",num];
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    NSDictionary *parameters = @{@"recharge":[NSString stringWithFormat:@"%d",num]};
//    NSDictionary *parameters = @{@"recharge":@"6"};
//    parameters = [[NSDictionary alloc] init];
//    [parameters setValue:num forKey:@"recharge"];
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/iosCharge" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 1013)
         {
             UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器获取记录失败，若余额没增加，请稍后点击屏幕下方找回汉点" preferredStyle:UIAlertControllerStyleAlert];
             
             UIAlertAction *okeyAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil];
             
             [alter addAction:okeyAction];
             
             [self presentViewController:alter animated:YES completion:nil];
             
             NSDate *date = [NSDate date];
             
             NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
             
             
             [formatter setDateStyle:NSDateFormatterMediumStyle];
             
             [formatter setTimeStyle:NSDateFormatterShortStyle];
             
             [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
             NSString *dateTime = [formatter stringFromDate:date];
        
             [self openDataBase];
             [self createTable];
             [self insertInformationWithmoney:insertNum Time:dateTime];
             [self closeDataBase];
         }
         else
         {
         [self.walletView showRecharView:YES];
         [self getMoneyNum];
         
         [self getPayHistory];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络异常，若余额没增加，请稍后点击屏幕下方找回汉点" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *okeyAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil];
        
        [alter addAction:okeyAction];
        
        [self presentViewController:alter animated:YES completion:nil];
        
        NSDate *date = [NSDate date];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        
        [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        NSString *dateTime = [formatter stringFromDate:date];
        
        [self openDataBase];
        [self createTable];
        [self insertInformationWithmoney:insertNum Time:dateTime];
        [self closeDataBase];


    }];
    

}

//获取历史记录
-(void)getPayHistory{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
  
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];

    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/ChargeRecord" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 200)
         {
             self.walletView.payHistoryDic = responseObject[@"result"];
             
             [self.walletView reloadTableView];
         }
         else if ([responseObject[@"status"] integerValue] == 199)
         {
             UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"您还未登录，请先登录"] preferredStyle:UIAlertControllerStyleAlert];
             
             [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                 [self dismissViewControllerAnimated:true completion:nil];
                 
             }]];
             
             [alert addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                 //self.navigationController.navigationBar.hidden = NO;
                LoginViewController *vc = [[LoginViewController alloc] init];
                 UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
              
                 [self presentViewController:nav animated:YES completion:nil];
                 
             }]];
             
             [self presentViewController:alert animated:YES completion:nil];
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         
     }];
}

//获取余额
-(void)getMoneyNum{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/ViewWallet" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 200) {
             self.walletView.balanceMoney.text = responseObject[@"result"][@"rest"];
             [self.walletView.balanceMoney sizeToFit];
         }
     }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         NSLog(@"%@",error);
     }];
}

-(void)find:(NSArray *)array{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *parameters = @{
                                 @"recharge":[NSString stringWithFormat:@"%@",array[0]],
                                 @"time":[NSString stringWithFormat:@"%@",array[1]]
                                 };
    
    NSString *cookie = [user objectForKey:@"Cookie"];
    
    NSLog(@"%@",cookie);
    
    [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    
    
    [manager POST:@"http://dahan-api.heiyou.net/index.php/home/user/chargeForIOS" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);
         if ([responseObject[@"status"] integerValue] == 200)
         {
             [SVProgressHUD showSuccessWithStatus:@"找回成功"];
             [self openDataBase];
             [self createTable];
             [self deleteInformation];
             [self closeDataBase];
             [self.walletView showRecharView:YES];
             [self getMoneyNum];
             
             [self getPayHistory];

         }
         else
         {
             [SVProgressHUD showErrorWithStatus:@"找回失败，请稍后再试"];
         }
     }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         [SVProgressHUD showErrorWithStatus:@"找回失败，请确认网络"];

     }];
}
#pragma mark - 数据库操作
//配置数据库路径,打开数据库
-(void)openDataBase{
    //创建数据库,并打开,获取数据库路径
    NSString *databaseFilePath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //设置数据库的路径和名称
    NSString *dataBasePath = [[NSString alloc] initWithString:[databaseFilePath stringByAppendingPathComponent:@"fsapp.sqlite"]];
    //打开数据库,数据库文件不存在时,自动创建
    if (sqlite3_open([dataBasePath UTF8String], &db) == SQLITE_OK) {
        NSLog(@"sqlite database is opened");
    }else{
        NSLog(@"sqlite database open fail");
    }
}

//创建表
- (void)createTable{
    //sql语句
    /*
     *create table if not exists 如果表不存在时自动创建
     *autoincrement 自增属性
     */
    NSString *createTableSql = @"create table if not exists PayHistory(id integer primary key autoincrement,money text,time text)";
    
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [createTableSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据表创建成功");
    }else{
        NSLog(@"创建数据表失败:%s",error);
    }
}

//插入记录
- (BOOL)insertInformationWithmoney:(NSString *)money Time:(NSString *)time{
    //sql语句
    NSString *insertSql = [NSString stringWithFormat:@"insert into PayHistory(money,time) values('%@','%@')",money,time];
    //        NSString *insertSql = [NSString stringWithFormat:@"insert into CollectTable(stationName,busName,toWhere) values('110指挥中心','16路','浦南')"];
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [insertSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据插入成功");
        return YES;
    }else{
        NSLog(@"数据插入失败:%s",error);
        return NO;
    }
    
}

//查询
//查询我的收藏
-(NSMutableArray *)search{
    NSString *searchSql = [NSString stringWithFormat:@"select * from PayHistory limit 1"];
    
    //预编译sql语句产生的结果
    sqlite3_stmt *stmt;
    NSMutableArray *collectArray = [[NSMutableArray alloc] init];
    
    if (sqlite3_prepare_v2(db, [searchSql UTF8String], -1, &stmt, NULL) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            NSArray *array = [NSArray arrayWithObjects:[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)],[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)], nil];
            
            [collectArray addObjectsFromArray:array];
        }
    }else{
        NSLog(@"查询失败");
    }
    
    NSLog(@"%@",collectArray);
    
    return collectArray;
}

//删除记录
- (BOOL)deleteInformation{
    //sql语句
    //delete from tt where 排序的字段 in (select 排序的字段 from tt order by 排序的字段 limit 0,n-1)
    NSString *deleteSql =[NSString stringWithFormat:@"delete from PayHistory where id in (select id from PayHistory order by id limit 1)"] ;
    
    //用于保存错误信息
    char *error;
    
    if (sqlite3_exec(db, [deleteSql UTF8String], NULL, NULL, &error) == SQLITE_OK) {
        NSLog(@"数据删除成功");
        
        return YES;
    }else{
        NSLog(@"数据删除失败:%s",error);
        
        return NO;
    }
}

//关闭数据库
-(void)closeDataBase{
    sqlite3_close(db);
}


#pragma mark - 禁止屏幕旋转
-(BOOL)shouldAutorotate{
    return NO;
}
@end
